<template>
  <el-dialog
    v-model="visible"
    width="720px"
    top="6vh"
    :append-to-body="true"
    :close-on-click-modal="false"
    :show-close="canClose"
    class="unified-dialog bulk-progress-dialog"
  >
    <template #header>
      <DialogHeader
        :icon="headerIcon"
        :title="title"
        :description="subtitle"
        :type="headerType"
      />
    </template>

    <div class="progress-container">
      <!-- 操作提示 -->
      <el-alert
        v-if="!isCompleted"
        type="info"
        :closable="false"
        show-icon
        class="operation-tip"
      >
        <template #title>
          <span style="font-size: 13px;">💡 提示：请勿关闭此对话框，可点击下方"后台运行"按钮继续其他操作</span>
        </template>
      </el-alert>
      
      <!-- 总体进度 -->
      <div class="overall-progress">
        <div class="progress-stats">
          <span class="stat-item">
            <span class="stat-label">总计:</span>
            <span class="stat-value">{{ totalJobs }}</span>
          </span>
          <span class="stat-item success">
            <span class="stat-label">成功:</span>
            <span class="stat-value">{{ successCount }}</span>
          </span>
          <span class="stat-item error">
            <span class="stat-label">失败:</span>
            <span class="stat-value">{{ failureCount }}</span>
          </span>
          <span class="stat-item">
            <span class="stat-label">剩余:</span>
            <span class="stat-value">{{ remainingCount }}</span>
          </span>
        </div>
        <el-progress
          :percentage="progressPercentage"
          :status="progressStatus"
          :stroke-width="20"
        />
      </div>

      <!-- 当前处理的作业 -->
      <div v-if="currentJob" class="current-job">
        <el-card shadow="never">
          <div class="current-job-header">
            <el-icon class="rotating"><Loading /></el-icon>
            <span>正在处理</span>
          </div>
          <div class="current-job-name">{{ currentJob }}</div>
        </el-card>
      </div>

      <!-- 作业列表 -->
      <div class="jobs-list">
        <el-scrollbar max-height="300px">
          <div
            v-for="(job, index) in jobResults"
            :key="index"
            class="job-item"
            :class="job.status"
          >
            <div class="job-item-content">
              <el-icon v-if="job.status === 'pending'" class="job-icon"><Clock /></el-icon>
              <el-icon v-else-if="job.status === 'processing'" class="job-icon rotating"><Loading /></el-icon>
              <el-icon v-else-if="job.status === 'success'" class="job-icon"><CircleCheck /></el-icon>
              <el-icon v-else-if="job.status === 'error'" class="job-icon"><CircleClose /></el-icon>
              
              <span class="job-name">{{ job.name }}</span>
              
              <el-tag
                v-if="job.status === 'success'"
                type="success"
                size="small"
                effect="light"
              >
                成功
              </el-tag>
              <el-tag
                v-else-if="job.status === 'error'"
                type="danger"
                size="small"
                effect="light"
              >
                失败
              </el-tag>
              <el-tag
                v-else-if="job.status === 'processing'"
                type="warning"
                size="small"
                effect="light"
              >
                处理中
              </el-tag>
              <el-tag
                v-else
                type="info"
                size="small"
                effect="light"
              >
                等待中
              </el-tag>
            </div>
            <div v-if="job.error" class="job-error">
              <el-icon><Warning /></el-icon>
              <span>{{ job.error }}</span>
            </div>
          </div>
        </el-scrollbar>
      </div>

      <!-- 完成提示 -->
      <div v-if="isCompleted" class="completion-message">
        <el-alert
          :type="hasErrors ? 'warning' : 'success'"
          :closable="false"
          show-icon
        >
          <template #title>
            <span v-if="!hasErrors">
              🎉 所有作业已处理完成！
            </span>
            <span v-else>
              ⚠️ 批量操作完成，部分作业处理失败
            </span>
          </template>
        </el-alert>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!isCompleted"
          @click="handleCancel"
          type="danger"
          plain
        >
          <el-icon><Close /></el-icon>
          取消任务
        </el-button>
        <el-button
          v-if="!isCompleted"
          @click="handleBackground"
          type="info"
          plain
        >
          <el-icon><Connection /></el-icon>
          后台运行
        </el-button>
        <el-button
          v-if="isCompleted"
          type="primary"
          @click="handleClose"
        >
          关闭
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onUnmounted } from 'vue'
import {
  Loading,
  CircleCheck,
  CircleClose,
  Warning,
  Clock,
  Connection,
  Close
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import DialogHeader from '@/components/DialogHeader.vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: '批量操作进度'
  },
  subtitle: {
    type: String,
    default: '正在处理批量操作'
  }
})

const emit = defineEmits(['update:modelValue', 'complete', 'background', 'cancel'])

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 进度状态
const totalJobs = ref(0)
const currentIndex = ref(0)
const currentJob = ref('')
const jobResults = ref([])
const isCompleted = ref(false)
const canClose = ref(false)

// 防抖定时器
let backgroundClickTimer = null

// 统计数据
const successCount = computed(() => 
  jobResults.value.filter(j => j.status === 'success').length
)

const failureCount = computed(() => 
  jobResults.value.filter(j => j.status === 'error').length
)

const remainingCount = computed(() => 
  totalJobs.value - successCount.value - failureCount.value
)

const progressPercentage = computed(() => {
  if (totalJobs.value === 0) return 0
  return Math.round(((successCount.value + failureCount.value) / totalJobs.value) * 100)
})

const progressStatus = computed(() => {
  if (!isCompleted.value) return undefined
  if (failureCount.value > 0) return 'warning'
  return 'success'
})

const hasErrors = computed(() => failureCount.value > 0)

const headerIcon = computed(() => {
  if (!isCompleted.value) return 'Loading'
  if (hasErrors.value) return 'Warning'
  return 'CircleCheck'
})

const headerType = computed(() => {
  if (!isCompleted.value) return 'info'
  return hasErrors.value ? 'warning' : 'success'
})

// 初始化
const initProgress = (jobs) => {
  totalJobs.value = jobs.length
  currentIndex.value = 0
  currentJob.value = ''
  isCompleted.value = false
  canClose.value = false
  jobResults.value = jobs.map(job => ({
    name: job.job_name || job,
    status: 'pending',
    error: null
  }))
}

// 开始处理作业
const startProcessing = (index) => {
  currentIndex.value = index
  currentJob.value = jobResults.value[index].name
  jobResults.value[index].status = 'processing'
}

// 标记作业成功
const markSuccess = (index) => {
  jobResults.value[index].status = 'success'
  jobResults.value[index].error = null
}

// 标记作业失败
const markError = (index, error) => {
  jobResults.value[index].status = 'error'
  jobResults.value[index].error = error
}

// 完成所有操作
const complete = () => {
  isCompleted.value = true
  canClose.value = true
  currentJob.value = ''
  emit('complete', {
    total: totalJobs.value,
    success: successCount.value,
    failure: failureCount.value
  })
}

// 取消任务
const handleCancel = () => {
  emit('cancel')
}

// 后台运行
const handleBackground = () => {
  // 防抖：如果已经有待执行的定时器，直接返回
  if (backgroundClickTimer) {
    console.log('[BulkProgressDialog] 防抖：忽略重复点击')
    return
  }
  
  console.log('[BulkProgressDialog] 后台运行按钮被点击')
  console.log('[BulkProgressDialog] 发送进度信息:', {
    current: successCount.value + failureCount.value,
    total: totalJobs.value
  })
  
  ElMessage.success({
    message: '✅ 任务已转入后台运行，您可以继续其他操作。点击右下角浮动按钮可重新查看进度',
    duration: 4000,
    showClose: true,
    grouping: true // 自动合并重复消息
  })
  
  // 发送后台任务进度信息
  emit('background', {
    current: successCount.value + failureCount.value,
    total: totalJobs.value
  })
  
  visible.value = false
  
  // 设置防抖定时器（300ms内不允许再次触发）
  backgroundClickTimer = setTimeout(() => {
    backgroundClickTimer = null
  }, 300)
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
}

// 清理定时器
onUnmounted(() => {
  if (backgroundClickTimer) {
    clearTimeout(backgroundClickTimer)
    backgroundClickTimer = null
  }
})

// 暴露方法和数据供父组件调用
defineExpose({
  initProgress,
  startProcessing,
  markSuccess,
  markError,
  complete,
  jobResults  // 暴露文件列表，用于根据文件名查找索引
})
</script>

<style scoped>
.progress-container {
  padding: 10px 0;
}

.operation-tip {
  margin-bottom: 16px;
  border-radius: 8px;
  background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
  border: 1px solid #90caf9;
}

.overall-progress {
  margin-bottom: 24px;
}

.progress-stats {
  display: flex;
  justify-content: space-around;
  margin-bottom: 16px;
  padding: 16px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e8ecf1 100%);
  border-radius: 12px;
  box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.05);
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.stat-label {
  font-size: 12px;
  color: #909399;
  font-weight: 500;
}

.stat-value {
  font-size: 24px;
  font-weight: 700;
  color: #303133;
}

.stat-item.success .stat-value {
  color: #67c23a;
}

.stat-item.error .stat-value {
  color: #f56c6c;
}

.current-job {
  margin-bottom: 20px;
}

.current-job :deep(.el-card__body) {
  padding: 16px;
  background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
  border: 2px solid #409eff;
  border-radius: 12px;
}

.current-job-header {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #409eff;
  font-weight: 600;
  margin-bottom: 8px;
  font-size: 14px;
}

.current-job-name {
  font-size: 16px;
  font-weight: 700;
  color: #303133;
  padding: 8px 12px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}

.jobs-list {
  margin-bottom: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 12px;
  padding: 12px;
  background: #fafafa;
}

.job-item {
  padding: 12px;
  margin-bottom: 8px;
  background: white;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

.job-item:last-child {
  margin-bottom: 0;
}

.job-item.processing {
  background: linear-gradient(135deg, #fff7e6 0%, #ffe7ba 100%);
  border-color: #e6a23c;
  box-shadow: 0 2px 8px rgba(230, 162, 60, 0.2);
}

.job-item.success {
  background: linear-gradient(135deg, #f0f9ff 0%, #e1f5fe 100%);
  border-color: #67c23a;
}

.job-item.error {
  background: linear-gradient(135deg, #ffebee 0%, #ffcdd2 100%);
  border-color: #f56c6c;
}

.job-item-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.job-icon {
  font-size: 20px;
  flex-shrink: 0;
}

.job-item.pending .job-icon {
  color: #909399;
}

.job-item.processing .job-icon {
  color: #e6a23c;
}

.job-item.success .job-icon {
  color: #67c23a;
}

.job-item.error .job-icon {
  color: #f56c6c;
}

.job-name {
  flex: 1;
  font-weight: 500;
  color: #303133;
}

.job-error {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 8px;
  padding: 8px 12px;
  background: rgba(245, 108, 108, 0.1);
  border-radius: 6px;
  font-size: 12px;
  color: #f56c6c;
}

.job-error .el-icon {
  font-size: 14px;
  flex-shrink: 0;
}

.completion-message {
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 旋转动画 */
.rotating {
  animation: rotate 1.5s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 进度条样式 */
:deep(.el-progress__text) {
  font-size: 16px !important;
  font-weight: 700;
}

:deep(.el-progress-bar__outer) {
  border-radius: 10px;
  overflow: hidden;
  box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.1);
}

:deep(.el-progress-bar__inner) {
  border-radius: 10px;
  background: linear-gradient(90deg, #409eff 0%, #66b3ff 100%);
  transition: width 0.4s ease;
}

:deep(.el-progress.is-success .el-progress-bar__inner) {
  background: linear-gradient(90deg, #67c23a 0%, #85ce61 100%);
}

:deep(.el-progress.is-warning .el-progress-bar__inner) {
  background: linear-gradient(90deg, #e6a23c 0%, #f0c78a 100%);
}

/* 滚动条样式 */
:deep(.el-scrollbar__wrap) {
  overflow-x: hidden;
}
</style>
